#!/bin/bash

# 多插件分支切换脚本
# 使用方法: ./scripts/plugin-branch-switcher.sh [branch_name] [--all] [--list] [--status]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# 插件目录
PLUGINS_DIR="plugins"
# 插件列表文件
PLUGINS_LIST_FILE="scripts/plugins-list.txt"

# 显示帮助信息
show_help() {
    echo -e "${BLUE}🔌 多插件分支切换脚本${NC}"
    echo ""
    echo "使用方法:"
    echo "  $0 [branch_name] [选项]"
    echo ""
    echo "参数:"
    echo "  branch_name       要切换到的分支名称"
    echo ""
    echo "选项:"
    echo "  --all             切换所有插件到指定分支"
    echo "  --list            列出所有插件"
    echo "  --status          显示所有插件当前分支状态"
    echo "  --create          创建新分支并切换"
    echo "  --help            显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 --list                    # 列出所有插件"
    echo "  $0 --status                  # 显示所有插件状态"
    echo "  $0 feature/new-ui --all     # 切换所有插件到feature/new-ui分支"
    echo "  $0 hotfix/bug-123 --create  # 创建并切换到hotfix/bug-123分支"
    echo ""
}

# 获取插件列表
get_plugins_list() {
    if [ -f "$PLUGINS_LIST_FILE" ]; then
        cat "$PLUGINS_LIST_FILE"
    else
        # 自动扫描插件目录
        find "$PLUGINS_DIR" -maxdepth 1 -type d -name "*" | grep -v "^$PLUGINS_DIR$" | sed "s|$PLUGINS_DIR/||" | sort
    fi
}

# 检查插件是否为git仓库
is_git_repo() {
    local plugin_dir="$1"
    [ -d "$PLUGINS_DIR/$plugin_dir/.git" ]
}

# 获取插件当前分支
get_plugin_branch() {
    local plugin_dir="$1"
    if is_git_repo "$plugin_dir"; then
        cd "$PLUGINS_DIR/$plugin_dir"
        git branch --show-current 2>/dev/null || echo "unknown"
        cd - > /dev/null
    else
        echo "not-git"
    fi
}

# 检查插件是否有未提交的更改
has_uncommitted_changes() {
    local plugin_dir="$1"
    if is_git_repo "$plugin_dir"; then
        cd "$PLUGINS_DIR/$plugin_dir"
        [ -n "$(git status --porcelain)" ]
        local result=$?
        cd - > /dev/null
        return $result
    else
        return 1
    fi
}

# 列出所有插件
list_plugins() {
    echo -e "${BLUE}📋 插件列表:${NC}"
    echo ""
    
    local plugins=($(get_plugins_list))
    local total_plugins=${#plugins[@]}
    
    echo -e "${CYAN}总计: $total_plugins 个插件${NC}"
    echo ""
    
    for plugin in "${plugins[@]}"; do
        if [ -d "$PLUGINS_DIR/$plugin" ]; then
            local branch=$(get_plugin_branch "$plugin")
            local status_icon=""
            
            if [ "$branch" = "not-git" ]; then
                status_icon="${YELLOW}⚠️${NC}"
            elif has_uncommitted_changes "$plugin"; then
                status_icon="${RED}🔴${NC}"
            else
                status_icon="${GREEN}🟢${NC}"
            fi
            
            printf "%-30s %s %s\n" "$plugin" "$status_icon" "$branch"
        fi
    done
    echo ""
}

# 显示插件状态
show_plugins_status() {
    echo -e "${BLUE}📊 插件状态概览:${NC}"
    echo ""
    
    local plugins=($(get_plugins_list))
    local total_plugins=${#plugins[@]}
    local git_plugins=0
    local dirty_plugins=0
    local clean_plugins=0
    
    echo -e "${CYAN}插件总数: $total_plugins${NC}"
    echo ""
    
    for plugin in "${plugins[@]}"; do
        if [ -d "$PLUGINS_DIR/$plugin" ]; then
            local branch=$(get_plugin_branch "$plugin")
            
            if [ "$branch" = "not-git" ]; then
                echo -e "${YELLOW}⚠️  $plugin${NC} - 不是git仓库"
            else
                ((git_plugins++))
                if has_uncommitted_changes "$plugin"; then
                    echo -e "${RED}🔴 $plugin${NC} - $branch (有未提交更改)"
                    ((dirty_plugins++))
                else
                    echo -e "${GREEN}🟢 $plugin${NC} - $branch"
                    ((clean_plugins++))
                fi
            fi
        fi
    done
    
    echo ""
    echo -e "${BLUE}统计信息:${NC}"
    echo -e "  Git仓库: $git_plugins"
    echo -e "  干净状态: $clean_plugins"
    echo -e "  有更改: $dirty_plugins"
    echo -e "  非Git: $((total_plugins - git_plugins))"
    echo ""
}

# 切换单个插件分支
switch_plugin_branch() {
    local plugin="$1"
    local target_branch="$2"
    local create_branch="$3"
    
    if [ ! -d "$PLUGINS_DIR/$plugin" ]; then
        echo -e "${YELLOW}⚠️  插件 $plugin 不存在，跳过${NC}"
        return 1
    fi
    
    if ! is_git_repo "$plugin"; then
        echo -e "${YELLOW}⚠️  插件 $plugin 不是git仓库，跳过${NC}"
        return 1
    fi
    
    cd "$PLUGINS_DIR/$plugin"
    
    # 检查当前分支
    local current_branch=$(git branch --show-current)
    
    # 检查是否有未提交的更改
    if has_uncommitted_changes "$plugin"; then
        echo -e "${RED}🔴 $plugin: 有未提交的更改，请先处理${NC}"
        cd - > /dev/null
        return 1
    fi
    
    # 检查目标分支是否存在
    if [ "$create_branch" = "true" ]; then
        echo -e "${BLUE}🔄 $plugin: 创建并切换到 $target_branch${NC}"
        git checkout -b "$target_branch"
    else
        if git show-ref --verify --quiet refs/heads/"$target_branch"; then
            echo -e "${BLUE}🔄 $plugin: 切换到 $target_branch${NC}"
            git checkout "$target_branch"
        else
            echo -e "${YELLOW}⚠️  $plugin: 分支 $target_branch 不存在${NC}"
            cd - > /dev/null
            return 1
        fi
    fi
    
    # 拉取最新代码
    echo -e "${CYAN}📥 $plugin: 拉取最新代码${NC}"
    git pull origin "$target_branch" 2>/dev/null || echo -e "${YELLOW}⚠️  无法拉取远程分支${NC}"
    
    cd - > /dev/null
    echo -e "${GREEN}✓ $plugin: 成功切换到 $target_branch${NC}"
    return 0
}

# 切换所有插件分支
switch_all_plugins_branch() {
    local target_branch="$1"
    local create_branch="$2"
    
    echo -e "${BLUE}🚀 开始切换所有插件到分支: $target_branch${NC}"
    echo ""
    
    local plugins=($(get_plugins_list))
    local total_plugins=${#plugins[@]}
    local success_count=0
    local failed_count=0
    local skipped_count=0
    
    for plugin in "${plugins[@]}"; do
        echo -e "${CYAN}处理插件: $plugin${NC}"
        
        if switch_plugin_branch "$plugin" "$target_branch" "$create_branch"; then
            ((success_count++))
        else
            ((failed_count++))
        fi
        
        echo ""
    done
    
    echo -e "${BLUE}📊 切换结果统计:${NC}"
    echo -e "  ${GREEN}成功: $success_count${NC}"
    echo -e "  ${RED}失败: $failed_count${NC}"
    echo -e "  ${YELLOW}跳过: $skipped_count${NC}"
    echo -e "  ${CYAN}总计: $total_plugins${NC}"
    echo ""
    
    if [ $failed_count -gt 0 ]; then
        echo -e "${YELLOW}⚠️  有 $failed_count 个插件切换失败，请检查上述错误信息${NC}"
        return 1
    else
        echo -e "${GREEN}🎉 所有插件切换成功！${NC}"
        return 0
    fi
}

# 主函数
main() {
    local target_branch=""
    local create_branch="false"
    local show_list="false"
    local show_status="false"
    
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            -h|--help)
                show_help
                exit 0
                ;;
            --all)
                if [ -z "$target_branch" ]; then
                    echo -e "${RED}错误: 使用 --all 时必须指定分支名称${NC}"
                    exit 1
                fi
                shift
                ;;
            --list)
                show_list="true"
                shift
                ;;
            --status)
                show_status="true"
                shift
                ;;
            --create)
                create_branch="true"
                shift
                ;;
            -*)
                echo -e "${RED}错误: 未知参数 $1${NC}"
                show_help
                exit 1
                ;;
            *)
                if [ -z "$target_branch" ]; then
                    target_branch="$1"
                else
                    echo -e "${RED}错误: 只能指定一个分支名称${NC}"
                    exit 1
                fi
                shift
                ;;
        esac
    done
    
    echo -e "${BLUE}🔌 多插件分支切换脚本${NC}"
    echo "========================================"
    echo ""
    
    # 检查插件目录是否存在
    if [ ! -d "$PLUGINS_DIR" ]; then
        echo -e "${RED}错误: 插件目录 $PLUGINS_DIR 不存在${NC}"
        exit 1
    fi
    
    # 执行相应操作
    if [ "$show_list" = "true" ]; then
        list_plugins
    elif [ "$show_status" = "true" ]; then
        show_plugins_status
    elif [ -n "$target_branch" ]; then
        if [ "$2" = "--all" ]; then
            switch_all_plugins_branch "$target_branch" "$create_branch"
        else
            echo -e "${RED}错误: 请使用 --all 参数来切换所有插件${NC}"
            exit 1
        fi
    else
        echo -e "${YELLOW}请指定要执行的操作${NC}"
        show_help
        exit 1
    fi
}

# 执行主函数
main "$@" 